<template>
  <a-card :bordered="false" style="height: 100%">
    <div class="table-page-search-wrapper">
      <HKAdvSearch :queryInfo="queryInfo" :paramNo="paramNo" :dictProperties="table.dictProperties" @search="searchByQuery"></HKAdvSearch>
    </div>

    <div class="table-operator" style="margin: 1% auto">
      <a-button type="primary" size="small" icon="plus-circle-o" @click="add" v-show="editable">新增</a-button>
      <a-button type="primary" size="small" icon="minus-circle-o" @click="deleteSelected" v-show="batchDeletable">删除</a-button>
      <a-button type="primary" size="small" icon="download" @click="exportExcel" v-show="exportable">导出</a-button>
    </div>

    <a-table
        ref="tableRef"
        size="middle"
        rowKey="rowKey"
        bordered
        :columns="columnFilter(table.columns)"
        :dataSource="table.dataSource"
        :pagination="table.pagination"
        :loading="table.loading"
        :scroll="table.scroll"
        :rowSelection="rowSelection"
        @change="handleChangeInTable"
        style="min-height: 300px"
    >
      <template #action="{ text, record }">
        <a v-show="editable === 1" @click="edit(record)">编辑</a>
        <a-divider type="vertical"/>
        <a-dropdown>
          <a class="ant-dropdown-link">更多 <a-icon type="down"/></a>
          <template #overlay>
            <a-menu>
              <a-menu-item v-show="deletable === 1" @click="view(record)">
                详细
              </a-menu-item>
              <a-menu-item v-for="m in extraMemus" :key="m.id" v-if="m.id === table.reportCode" @click="m.func(record)">
                {{ m.title }}
              </a-menu-item>
              <a-menu-item v-show="deletable === 1">
                <a-popconfirm title="确定删除吗?" @confirm="() => del(record)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
      <template #sub="{ text, record, column }" @click="getSubQuery(text, column, null)">{{ text }}</template>
    </a-table>

    <a-modal :title="subTable.title"
             :width="820"
             :visible="subTable.visible"
             :confirmLoading="subTable.uploading"
             @cancel="handleCancel"
    >
      <template #footer>
        <p>{{ subTable.footer }}</p>
      </template>
      <a-table :columns="columnFilter(subTable.columns)"
               size="small"
               rowKey="rowKey"
               :bordered="false"
               :pagination="subTable.pagination"
               :loading="subTable.loading"
               :scroll="subTable.scroll"
               :data-source="subTable.dataSource"
               @change="handleChangeInSubTable"  />
    </a-modal>
    <RecordModal ref="modalMain" @ok="modalFormOk" :columns="table.columns" :paramNo="paramNo2" :reportCode="table.reportCode" :dictProperties="table.dictProperties"></RecordModal>
    <DetailModal ref="modalDetail" @toEdit="edit" :columns="table.columns" :paramNo="paramNo2" :infoName="title" :dictProperties="table.dictProperties"></DetailModal>
  </a-card>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { deleteAction, downFile, getAction } from '@/utils/request';
import { values2Texts } from '@/utils/my.js';
import { filterObj } from '@/utils/util.js';
import HKAdvSearch from '@/components/YGCrm/YGAdvSearch';
import RecordModal from '@/views/modules/RecordModal';
import DetailModal from "@/views/modules/basicModal/DetailModal";
import { message, Modal } from 'ant-design-vue';


// 路由和路由参数
const route = useRoute();
const router = useRouter();


// 响应式数据
const title = ref('');
const paramNo = ref(3);
const paramNo2 = ref(3);
const exportable = ref(false);
const printable = ref(false);
const editable = ref(false);
const deletable = ref(false);
const batchDeletable = ref(false);
const recyclable = ref(false);
const primaryKey = ref('id');
const widthType = ref(1);
const queryInfo = ref([]);
const queryParamsMap = ref({});
const selfParam = ref({});
const toggleSearchStatus = ref(false);
const description = ref('在线报表功能测试页面');
const extraMemus = ref([{
  id: '1492708397563289601',
  title: "合同",
  func: (r) => {
    router.push({
      path: `/finance/contract`,
      query: { id: r.id }
    });
  }
}]);

// 表格数据
const table = reactive({
  loading: false,
  reportCode: '',
  cReportHeadName: "",
  columns: [],
  dataSource: [],
  dictProperties: {},
  selectedRowKeys: [],
  selectionRows: [],
  scroll: { x: false },
  pagination: {
    current: 1,
    pageSize: 10,
    pageSizeOptions: ['10', '20', '30', '50'],
    showTotal: (total, range) => `${range[0]}-${range[1]} 共${total}条`,
    showQuickJumper: true,
    showSizeChanger: true,
    total: 0
  },
  columnAveWidth: 150,
  sorter: {
    column: '',
    order: 'desc'
  }
});

// 子表格数据
const subTpl = {
  title: "子查询",
  visible: false,
  loading: false,
  columnsUpdate: true,
  reportCode: '',
  cReportHeadName: "",
  columns: [],
  dataSource: [],
  dictProperties: {},
  selectedRowKeys: [],
  selectionRows: [],
  scroll: { x: false },
  pagination: {
    current: 1,
    pageSize: 10,
    pageSizeOptions: ['10', '20', '30'],
    showTotal: (total, range) => `${range[0]}-${range[1]} 共${total}条`,
    showQuickJumper: true,
    showSizeChanger: true,
    total: 0
  },
  columnAveWidth: 190,
  sorter: {
    column: '',
    order: 'desc'
  },
  text: '',
  column: {},
  footer: ''
};

const subTable = reactive({ ...subTpl });

// 组件引用
const tableRef = ref(null);
const modalMain = ref(null);
const modalDetail = ref(null);

// 计算属性
const rowSelection = computed(() => {
  if (batchDeletable.value || exportable.value) {
    return {
      onChange: (selectedRowKeys, selectedRows) => {
        table.selectedRowKeys = selectedRowKeys;
        table.selectionRows = selectedRows;
      }
    };
  }
});

const queryParam = computed({
  get() {
    return queryParamsMap.value[table.reportCode];
  },
  set(newVal) {
    queryParamsMap.value[table.reportCode] = newVal;
  }
});

// 方法定义
function columnFilter(columns) {
  return columns.filter(c => c.is_show === 1 || c.dataIndex === "operation");
}



function add() {
  modalMain.value.add();
}

function edit(record) {
  if (primaryKey.value in record) {
    modalMain.value.edit(record, primaryKey.value);
  } else {
    Modal.error({ content: "没有业务主键，不能编辑！" });
  }
}

function view(record) {
  modalDetail.value.detail(record);
}

function del(record) {
  if (primaryKey.value in record) {
    const httpurl = '/reportConfig/config/record-delete';
    const param = { confId: table.reportCode };
    param[primaryKey.value] = record[primaryKey.value];
    deleteAction(httpurl, param)
        .then((res) => {
          if (res.success) {
            message.success(res.message);
            loadData();
          } else {
            message.warning(res.message);
          }
        });
  } else {
    Modal.error({ content: "没有业务主键，不能删除！" });
  }
}

function deleteSelected() {
  if (table.selectionRows.length === 0) {
    message.error("请先选择记录！");
    return;
  }

  const ids = table.selectionRows.map(s => s[primaryKey.value]);
  if (ids.length > 0) {
    const httpurl = '/reportConfig/config/record-delBatch';
    const param = { confId: table.reportCode, ids };
    deleteAction(httpurl, param)
        .then((res) => {
          if (res.success) {
            message.success(res.message);
            loadData();
          } else {
            message.warning(res.message);
          }
        });
  } else {
    Modal.error({ content: "没有业务主键，不能删除！" });
  }
}

function modalFormOk() {
  loadData();
}

function getSubQuery(text, column, arg) {
  const [rptCode, field] = column['field_href'].split(".");
  const params = Object.assign({}, table.sorter);
  subTable.reportCode = rptCode;
  subTable.column = column;
  subTable.text = text;
  params[field] = subTable.text;
  params.pageNo = subTable.pagination.current;
  params.pageSize = subTable.pagination.pageSize;
  loadData(0, params, subTable);
  subTable.visible = true;
}

function handleCancel() {
  Object.assign(subTable, { ...subTpl });
}

function setCode() {
  const tmp = route.fullPath.split("/")[3];
  table.reportCode = atob(tmp);
}

function initParamsInfo() {
  if (!table.reportCode) return false;

  if (!queryParam.value) {
    queryParam.value = {};
  }

  selfParam.value = {};
  getAction(`/report/config/getParamsInfo${table.reportCode}`).then((res) => {
    if (res.success && res.result && res.result.length > 0) {
      for (const i of res.result) {
        selfParam.value[`self_${i.paramName}`] = route.query[i.paramName] || "";
      }
    } else {
      message.warning(res.message);
    }
  });
}

function initQueryInfo() {
  if (!table.reportCode) return false;

  const actions = [
    getAction(`/report/config/getColumns${table.reportCode}`),
    getAction(`/report/config/getQueryInfo${table.reportCode}`),
    getAction(`/report/config/getConfigInfo${table.reportCode}`)
  ];

  Promise.all(actions).then((res) => {
    const [{ result: { columns, dictProperties, cReportHeadName } }, { result: queryInfos, success }, { result: config }] = res;

    if (dictProperties && !$.isEmptyObject(dictProperties)) {
      table.dictProperties = dictProperties;
    }

    if (config) {
      title.value = config.name;
      printable.value = config.printable;
      exportable.value = config.exportable;
      editable.value = config.editable;
      deletable.value = config.deletable;
      batchDeletable.value = config.batchDeletable;
      if (config.paramNoPerLine) paramNo.value = config.paramNoPerLine;
      if (config.paramNoPerLine2) paramNo2.value = config.paramNoPerLine2;
      if (config.widthType) widthType.value = config.widthType;
      if (config.primaryKey) {
        let k = config.primaryKey;
        if (k.indexOf(".") !== -1) k = k.split(".")[1];
        primaryKey.value = k;
      }
    }

    if (columns) {
      columns.forEach(col => {
        col.required = false;
        if (col.is_required === 1 || col.is_required === 3) col.required = true;
        if (col.title.endsWith('*')) {
          col.required = true;
          col.title = col.title.replace(/\*$/g, '');
        }

        if (columns.length > 7 || widthType.value === 2) {
          if (col.width) col.width = Number(col.width.replace('%', ''));
        }

        if (dictProperties && dictProperties[col.dataIndex] && col.is_show === 1) {
          const options = table.dictProperties[col.dataIndex].options;
          col.customRender = (t) => values2Texts(t, options) || t;
        }

        if (col.field_href && col.field_href.length > 3) {
          col.scopedSlots = { customRender: 'sub' };
        }

        if (col.dictCode && col.dictCode.length > 3) {
          col.customRender = (text) => {
            if (!text) return '';
            return values2Texts(text + "", table.dictProperties[col.dataIndex].options);
          };
        }
      });

      const columnWidth = table.columnAveWidth;
      columns.width = columnWidth;

      if (columns.length > 7) {
        columns[0].fixed = 'left';
        columns[columns.length - 1].fixed = 'right';
        table.scroll.x = columns.length * columnWidth;
      }

      table.columns = [...columns];

      if (editable.value === 1 || deletable.value === 1) {
        table.columns.push({
          title: '操作',
          dataIndex: 'operation',
          fixed: 'right',
          width: 120,
          scopedSlots: { customRender: 'action' }
        });
      }

      table.cReportHeadName = cReportHeadName;
    }

    if (success) {
      queryInfos.forEach(q => {
        q.label = q.label.replace(/\*$/g, '');
        if (q.field_type === 1) q.rule = [{ pattern: /^([1-9][0-9]*(\.[0-9]+)*)*$/, message: '请输入数值!' }];
        if (q.field_type === 5) q.rule = [{ pattern: /^([1-9][0-9]*)*$/, message: '请输入整数!' }];
      });
      queryInfo.value = queryInfos;
    } else {
      message.warning(res.message);
    }
  });
}

function loadData(arg, params, tableObj) {
  const targetTable = tableObj || table;
  const reportCode = targetTable.reportCode || table.reportCode;
  if (!reportCode) return false;

  if (arg) {
    table.pagination.current = arg;
  }

  // 实现数据加载逻辑
}

// 生命周期
onMounted(() => {
  setCode();
  initParamsInfo();
  initQueryInfo();
});

// 路由监听
watch(
    () => route.fullPath,
    () => {
      setCode();
      initParamsInfo();
      initQueryInfo();
      loadData();
    }
);
</script>


<style scoped>
  .div {
    display: flex;
    align-items: center;
    height: 500px
  }
</style>
